import requests
import os
from video_cvt import cvt_ts2mp4
import urllib3
from tqdm import tqdm


def download_m3u8_video(url, file_path):
    print('正在获取m3u8视频列表...')
    r = requests.get(url, verify=False)
    if r.status_code != 200:
        print('m3u8视频下载链接无效')
        return False
    
    m3u8_list = r.text.split('\n')
    m3u8_list = [i for i in m3u8_list if i and i[0] != '#']
    print(f'm3u8视频列表: {m3u8_list}')

    ts_list = []
    for ts_url in m3u8_list:
        ts_url = url.rsplit('/', 1)[0] + '/' + ts_url
        ts_list.append(ts_url)

    with open(file_path, 'wb') as f:
        print('正在下载视频...')
        pbar = tqdm(total=len(m3u8_list))
        for ts_url in ts_list:
            r = requests.get(ts_url, verify=False)
            if r.status_code == 200:
                f.write(r.content)
                pbar.update(1)
    print('m3u8视频下载完成')
    return True


if __name__ == '__main__':
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    url = 'https://trvdpx9.buzz/videos/202310/07/652243db0937bc103fec6a49/aac0c2/index.m3u8'
    mp4_file = '长发初中生自拍嫩屄'

    download_m3u8_video(url, f'{mp4_file}.ts')
    cvt_ts2mp4(f'{mp4_file}.ts', f'{mp4_file}.mp4')
    os.remove(f'{mp4_file}.ts')